package com.itheima.stock.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.itheima.stock.common.StockInConfig;
import com.itheima.stock.common.domain.*;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.service.StockService;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.pojo.StockBusiness;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service("stockService")
@Slf4j
public class StockServiceImpl implements StockService {
    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private StockInConfig stockInConfig;
    //股票大盘数据详情表
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    //    @Override
//    public R<List<StockBusiness>> getAllStockBusiness() {
//        List<StockBusiness> list= stockBusinessMapper.findAll();
//        return R.ok(list);
//    }
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;

    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    @Override
    public R<List<StockBusiness>> getAllStockBusiness() {
        return null;
    }

    @Override
    public R<List<StockBusiness>> findAllBusiness() {
        List<StockBusiness> list = stockBusinessMapper.findAll();
        return R.ok(list);
    }

    //获取国内大盘的实时数据
    @Override
    public R<List<InnerMarketDomain>> innerIndexAll() {
        //1.获取国内大盘的id集合
        List<String> innerIds = stockInConfig.getInner();
        //2.获取最近最新的股票有效交易日
        String lastDate = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        //TODO 后续删除
        lastDate = "20211226105600";//TODO 后续大盘数据实时拉去,将改行注释掉
        //3.调用mapper查询指定日期下对应的国内大盘数据
        List<InnerMarketDomain> maps = stockMarketIndexInfoMapper.selectByIdAndDate(innerIds, lastDate);
        //组装响应的数据
        /*CollectionUtils.isNotEmpty() 集合包含null,size=0等多种情况
        而== null 只能用来判断是否为null*/
        if (CollectionUtils.isEmpty(maps)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(maps);
    }

    @Override
    public R<List<SectorBlockDomain>> sectorAllLimit() {
        //调用mapper接口获取数据
        List<SectorBlockDomain> infos = stockBlockRtInfoMapper.sectorAllLimit();
        //组装数据
        if (CollectionUtils.isEmpty(infos)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(infos);
    }

    @Override
    public R<List<StockIncreaseDomain>> stockIncreaseLimit() {
        List<StockIncreaseDomain> infos = stockRtInfoMapper.stockIncreaseLimit();
        if (CollectionUtils.isEmpty(infos)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(infos);
    }

    @Override
    public R<PageResult<StockIncreaseDomain>> stockAllLimit(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<StockIncreaseDomain> infos = stockRtInfoMapper.stockAll();
        if (CollectionUtils.isEmpty(infos)) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        PageInfo<StockIncreaseDomain> pageInfo = new PageInfo<>(infos);
        PageResult<StockIncreaseDomain> pageResult = new PageResult<>(pageInfo);
        return R.ok(pageResult);
    }

    @Override
    public R<Map> getStockUpDownCount() {
        String avlDate = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        //TODO 后续删除
        avlDate = "20220107092500";
        List<Map> upCount = stockRtInfoMapper.getUpDownCount(avlDate, 1);
        List<Map> downCount = stockRtInfoMapper.getUpDownCount(avlDate, 0);
        HashMap<String, List<Map>> info = new HashMap<>();
        info.put("upList", upCount);
        info.put("downList", downCount);
        return R.ok(info);
    }

    @Override
    public void stockExport(HttpServletResponse response, Integer page, Integer pageSize) {
        try {
            //1.设置响应数据的类型:excel
            response.setContentType("application/vnd.ms-excel");
            //2.设置响应数据的编码格式
            response.setCharacterEncoding("utf-8");
            //3.设置默认的文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("stockRt", "UTF-8");
            //设置默认文件名称
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //4.分页查询股票数据
            PageHelper.startPage(page, pageSize);
            List<StockIncreaseDomain> infos = stockRtInfoMapper.stockAll();

            //5.导出
            EasyExcel.write(response.getOutputStream(), StockIncreaseDomain.class).sheet("股票数据").doWrite(infos);
        } catch (IOException e) {
            log.info("股票excel数据导出异常，当前页：{}，每页大小：{}，异常信息：{}", page, pageSize, e.getMessage());
        }
    }

    @Override
    public R<Map> getStockTravolCompare() {
        DateTime tDay = DateTimeUtil.getLastDate4Stock(DateTime.now());
        //转字符串
        String tStr = DateTimeUtil.parseToString4Stock(tDay);
        //TODO 后续删除
        tStr = "2022-01-03 14:30:00";
        DateTime preDay = DateTimeUtil.getLastDate4Stock(DateTimeUtil.getPreDateTime(tDay));
        //转字符串
        String preStr = DateTimeUtil.parseToString4Stock(preDay);
        preStr = "2022-01-02 14:30:00";
        List<Map> nowData = stockMarketIndexInfoMapper.getStockTravol(stockInConfig.getInner(), tStr);
        List<Map> preData = stockMarketIndexInfoMapper.getStockTravol(stockInConfig.getInner(), preStr);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("volList", nowData);
        map.put("yesVolList", preData);
        return R.ok(map);
    }

    /**
     * 功能描述：统计在当前时间下（精确到分钟），股票在各个涨跌区间的数量
     * 如果当前不在股票有效时间内，则以最近的一个有效股票交易时间作为查询时间点；
     *
     * @return 响应数据格式：
     * {
     * "code": 1,
     * "data": {
     * "time": "2021-12-31 14:58:00",
     * "infos": [
     * {
     * "count": 17,
     * "title": "-3~0%"
     * },
     * //...
     * ]
     * }
     */
    @Override
    public R<Map> stockUpDownScopeCount() {
        //1.获取当前时间下最近的一个股票交易时间 精确到秒
        String avlDate = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        //TODO 后续删除
        avlDate = "2022-01-06 09:55:00";
        //2.查询
        List<Map> maps = stockRtInfoMapper.stockUpDownScopeCount(avlDate);
        //3.获取去股票涨幅区间的集合
        List<String> upDownRange = stockInConfig.getUpDownRange();
        //将List集合下的字符串映射成Map对象
//        List<Map> orderMap = upDownRange.stream().map(key->{
//            Optional<Map> title = maps.stream().filter(map -> key.equals(map.get("title"))).findFirst();
//            //判断对应的map是否存在
//            Map tmp = null;
//            if(title.isPresent()){
//                tmp = title.get();
//            }else {
//                tmp = new HashMap();
//                tmp.put("title",key);
//                tmp.put("count",0);
//            }
//            return tmp;
//        }).collect(Collectors.toList());


        ArrayList<Map> orderMap = new ArrayList<>();
        for (String title : upDownRange) {
            Map tmp = null;
            for (Map map : maps) {
                if (title.equals(map.get("title"))) {
                    tmp = map;
                }
            }
            if (tmp == null) {
                tmp = new HashMap();
                tmp.put("title", title);
                tmp.put("count", 0);
            }
            orderMap.add(tmp);
        }
        HashMap<String, Object> data = new HashMap<>();
        data.put("time", avlDate);
        data.put("infos", orderMap);
        return R.ok(data);
    }

    @Override
    public R<List<ScreenTimeSharinDomain>> stockScreenTimeSharing(String code) {
        //1.获取最近有效的股票交易时间
        String avlDate = DateTimeUtil.getLastDateString4Stock(DateTime.now());
        //TODO 后续删除
        avlDate = "2022-01-06 09:25:00";
        List<ScreenTimeSharinDomain> infos = stockRtInfoMapper.stockScreenTimeSharing(code, avlDate);
        return R.ok(infos);
    }

    @Override
    public R<List<ScreenDklineDomain>> stockCreenDkLine(String code) {
       //获取当前日期前推20天
        Date forwardDate = DateTime.now().minusDays(20).toDate();
        //查询指定的股票在指定的日期范围内每天的股票统计数据
       List<ScreenDklineDomain> maps =stockRtInfoMapper.stockCreenDkLine(code,forwardDate);
        return R.ok(maps);
    }
}
